﻿using Microsoft.SharePoint.Administration;
using System.Collections.Generic;

namespace IPS.SP2013.DiagnosticsProvider
{

    /// <summary>
    /// Provides a diagnostic logging manager be used by your custom devs
    /// to write log entries based on your custom log categories definitions
    /// </summary>
    public class LogProvider : SPDiagnosticsServiceBase
    {

        #region Properties

        public static LogProvider _Current;

        public static LogProvider Current
        {
            get
            {
                if (_Current == null)
                {
                    _Current = new LogProvider();
                }

                return _Current;
            }
        }

        #endregion

        #region Override Methods

        /// <summary>
        /// Override the base class method to load the SPDiagnosticsArea object 
        /// to be used by the custom log provider
        /// </summary>
        /// <returns>Returns the diagnostics area with your custom log categories 
        /// defined in the dictionary</returns>
        protected override IEnumerable<SPDiagnosticsArea> ProvideAreas()
        {
            List<SPDiagnosticsArea> diagnosticArea = new List<SPDiagnosticsArea>();
            List<SPDiagnosticsCategory> categories = new List<SPDiagnosticsCategory>();

            foreach (KeyValuePair<int, Constants.CustomLogCategory> customCategory in Constants.CustomLogCategories)
            {
                categories.Add(new SPDiagnosticsCategory(customCategory.Value.Name, customCategory.Value.TraceSeverity, customCategory.Value.EventSeverity, 0, customCategory.Value.Id));
            }

            diagnosticArea.Add(new SPDiagnosticsArea(Constants.Diagnostics_Area_Name, categories));

            return diagnosticArea;
        }

        #endregion

        #region Private Methods

        private LogProvider()
            : base(Constants.Diagnostics_Area_Name, SPFarm.Local)
        {

        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Static method to be used by your custom devs to write a new log entry
        /// </summary>
        /// <param name="categoryName">Specify your custom log category</param>
        /// <param name="message">Specify the log message</param>
        public static void WriteLogEntry(Constants.CategoryNames categoryName, string message)
        {
            SPDiagnosticsCategory category = LogProvider.Current.Areas[Constants.Diagnostics_Area_Name].Categories[categoryName.ToString()];
            LogProvider.Current.WriteTrace(category.Id, category, category.TraceSeverity, message);
        }

        #endregion

    }

}
